package com.novellotus.iov.carvice.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.bean.RxEstion;
import com.novellotus.iov.carvice.maps.PoiOverlay;
import com.novellotus.iov.carvice.maps.SensorEventHelper;
import com.novellotus.iov.carvice.retrofit.BaseArrayEntity;
import com.novellotus.iov.carvice.retrofit.BaseArrayObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

public class ServiceStationActivity extends BaseActivity implements LocationSource,
        AMapLocationListener, AMap.OnInfoWindowClickListener, AMap.OnMarkerClickListener, AMap.InfoWindowAdapter {

    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.hideView)
    View hideView;
    private AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private AMapLocation mCurrentLocation;
    private boolean mFirstFix = false;
    private Marker mLocMarker;
    private SensorEventHelper mSensorHelper;
    private PopupWindow popupWindow;
    public static final String LOCATION_MARKER_FLAG = "mylocation";
    private List<RxEstion> lists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapView.onCreate(savedInstanceState);
    }

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_service_station);
    }

    @Override
    public void init() {
        popupWindow = new PopupWindow();
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
        mSensorHelper = new SensorEventHelper(this);
        mSensorHelper.registerSensorListener();
        initLocation();
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setInfoWindowAdapter(this);
        tv_tittle.setText("服务站");
        getList();
    }


    /**
     * 获取角色列表
     */
    public void getList() {
        Observable<BaseArrayEntity<RxEstion>> observable = RetrofitFactory.getInstance().estations(SharedPreferencesUtils.getKey(this)[0]);
        observable.compose(RxSchedulers.<BaseArrayEntity<RxEstion>>compose())
                .subscribe(new BaseArrayObserver<RxEstion>(this) {

                    @Override
                    public void onSuccess(List<RxEstion> list) {
                        lists = list;
                        setServiceMarker();
                    }

                    @Override
                    public void onFail(int code, String msg) {

                    }

                    @Override
                    public void onError(String msg) {

                    }
                });
    }

    /**
     * return new MarkerOptions()
     * .position(new LatLng(poiItem.getLatLonPoint()
     * .getLatitude(), poiItem
     * .getLatLonPoint().getLongitude()))
     * .title(poiItem.getTitle()).snippet(poiItem.getSnippet())
     * .icon(getBitmapDescriptor(poiItem)).infoWindowEnable(false);
     */
    private void setServiceMarker() {

        for (RxEstion rxEstion : lists) {
            MarkerOptions options = new MarkerOptions();
            options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(),
                    R.mipmap.icon_service_station)));
            options.anchor(0.5f, 0.5f);
            options.title(rxEstion.getEname());
            options.position(new LatLng(rxEstion.getLat(), rxEstion.getLng()));
            aMap.addMarker(options).setObject(rxEstion);
        }

    }


    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setRotateGesturesEnabled(false);
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMinZoomLevel(4);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }


    private void destroyLocation() {
        if (mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(this);
            mLocationClient.onDestroy();
        }
    }

    /**
     * 初始化定位
     */
    private void initLocation() {
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationClient = new AMapLocationClient(this.getApplicationContext());
        mLocationClient.setLocationListener(this);
        mLocationClient.startLocation();
    }

    @OnClick(R.id.img_back)
    void back() {
        finish();
    }

    @OnClick(R.id.ibt_location)
    void clickLocation() {
        if (location != null) {
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }
    }


    /**
     * @param latlng 自定义可以旋转的marker
     */
    private void addMarker(LatLng latlng) {
        if (mLocMarker != null) {

            return;
        }
        MarkerOptions options = new MarkerOptions();
        options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(),
                R.mipmap.navi_map_gps_locked)));
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);

        mLocMarker.setTitle(LOCATION_MARKER_FLAG);
        mLocMarker.setClickable(false);
    }


    private void show(final Marker marker) {
        final RxEstion rxEstion = (RxEstion) marker.getObject();
        if (rxEstion != null) {
            View layout = View.inflate(this, R.layout.layout_service, null);
            TextView name = layout.findViewById(R.id.tv_name);
            TextView address = layout.findViewById(R.id.tv_address);
            TextView phone = layout.findViewById(R.id.tv_phone_value);
            phone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Observable.create(new ObservableOnSubscribe<Object>() {
                        @Override
                        public void subscribe(ObservableEmitter<Object> e) throws Exception {
                            e.onNext("");
                        }
                    }).compose(RxSchedulers.lifecycle(ServiceStationActivity.this)).throttleFirst(1, TimeUnit.SECONDS)
                            .compose(rxPermissions.ensureEach(Manifest.permission.CALL_PHONE)).subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(Permission permission) throws Exception {
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + rxEstion.getPhone()));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    });
                }
            });
            phone.setText(rxEstion.getPhone());
            ImageView img_navi = layout.findViewById(R.id.img_navi);
            img_navi.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startAMapNavi(marker);
                }
            });

            name.setText(rxEstion.getEname());
            address.setText(rxEstion.getAddress());
            //  marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_charging_choose));
            popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable(null, ""));
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                                                 @Override
                                                 public void onDismiss() {
//                                                     marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_service));
//                                                     marker.setPeriod(10);
                                                 }
                                             }
            );
            popupWindow.showAtLocation(hideView, Gravity.BOTTOM, 0, 0);
        }

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        deactivate();
        mFirstFix = false;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (aMap != null) {
            aMap.clear();
            aMap = null;
        }
        mListener = null;
        mLocMarker = null;

        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper = null;
        }
        mCurrentLocation = null;
        mLocationClient = null;
        mLocationOption = null;
        if (mLocMarker != null) {
            mLocMarker.destroy();
        }
        popupWindow = null;
        destroyLocation();
        mapView = null;
    }

    LatLng location;

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                location = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                if (!mFirstFix) {
                    mFirstFix = true;
                    addMarker(location);//添加定位图标
                    mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 10));
                } else {
                    mLocMarker.setPosition(location);

                    //   aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                }
                mCurrentLocation = amapLocation;
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    @Override
    public void activate(LocationSource.OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            mLocationOption.setInterval(20000);//隔20秒
            //设置定位监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            //  mLocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {
        return null;
    }


    private void startAMapNavi(Marker marker) {
        if (mLocationOption == null) {
            MyUtils.logInformation("mCurrentLocation空");
            return;
        }
        Intent intent = new Intent(ServiceStationActivity.this, RouteNaviActivity.class);
        intent.putExtra("gps", false);
        intent.putExtra("start", new NaviLatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));
        intent.putExtra("end", new NaviLatLng(marker.getPosition().latitude, marker.getPosition().longitude));
        startActivity(intent);
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        show(marker);
        return false;
    }


}
